const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

const jwtSecret = '123456';

const noLoginCfg = [
    {
        url:'/user/login',
        method:'POST'
    },
    {
        url:'/user/reg',
        method:'POST'
    }
];

const dbCfg={
    host:'localhost',
    user:'root',
    password:'cmsylds114',
    database:'thework'
}

module.exports = {
    noLogin: noLoginCfg,
    dbCfg:dbCfg,
    jwtSecret:jwtSecret
}

// 动态加载 SQL 脚本
const sqlFilePath = path.join(__dirname, '../sql/init.sql');
const sqlScript = fs.readFileSync(sqlFilePath, 'utf8');

async function initDatabase() {
    try {
        const connection = await mysql.createConnection({
            host: dbCfg.host,
            user: dbCfg.user,
            password: dbCfg.password
        });

        // 检查数据库是否存在
        const [rows] = await connection.query(
            'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?',
            [dbCfg.database]
        );

        console.log(`查询结果:`, rows);

        if (rows.length === 0) {
            console.log(`数据库 ${dbCfg.database} 不存在，正在创建...`);
            await connection.query(`CREATE DATABASE \`${dbCfg.database}\``);
            console.log(`数据库 ${dbCfg.database} 创建成功！`);
        } else {
            console.log(`数据库 ${dbCfg.database} 已存在，跳过创建。`);
        }

        await connection.end();

        // 重新连接到目标数据库
        const dbConnection = await mysql.createConnection({
            host: dbCfg.host,
            user: dbCfg.user,
            password: dbCfg.password,
            database: dbCfg.database
        });

        console.log(`已连接到数据库 ${dbCfg.database}`);

        // 执行SQL脚本
        console.log('正在检查是否需要执行SQL脚本...');
        const statements = sqlScript.split(/;[\r\n]+/).filter(statement => statement.trim());
        
        // 检查是否需要执行SQL脚本
        if (rows.length === 0) {
            console.log('数据库不存在，正在执行SQL脚本...');
            for (const statement of statements) {
                console.log(`执行 SQL: ${statement}`);
                await dbConnection.query(statement);
            }
            console.log('SQL脚本执行完成！');
        } else {
            console.log('数据库已存在，跳过SQL脚本执行。');
        }

        await dbConnection.end();
    } catch (error) {
        console.error('初始化数据库失败:', error);
    }
}

// 执行初始化
initDatabase();